package com.tianming.boot62.controller;

import com.tianming.boot62.entity.User;
import com.tianming.boot62.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper userMapper;

    @RequestMapping("/reg")
    public int reg(User user){
        User u = userMapper.selectByUsername(user.getUsername());
        if (u == null ){
            int i = userMapper.insertUser(user);
            if (i == 1) {
                return 1;
            }
        }
        return 0;
    }
    @RequestMapping("/login")
    public int login(User user, HttpSession session){
        User u = userMapper.selectByUsername(user.getUsername());
        if (u != null){ //用户存在
            if (user.getPassword().equals(u.getPassword()) ){
                //登录成功时把登录用户对象保存到session会话中
                session.setAttribute("user",u);
                return 1; //登录成功
            }else {
                return 2; //密码错误
            }
        }
        return 0; //用户不存在
    }
    @RequestMapping("/checkLogin")
    public User checkLogin(HttpSession session){
        User user = (User) session.getAttribute("user");
        // 此时给客户端返回的值如果是null ,sSpringMVC框架中
        // 负责把对象转成Json字符串的地方会直接转成"”空字符串
        // 也就是最终给客户端返回的并不是null而是""空字符串
        return user;
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        //删除会话中的user
        session.removeAttribute("user");
    }
}
